package com.tech.utils;

import cn.hutool.core.util.StrUtil;
import com.tech.model.ExtFuncEntity;
import com.tech.repo.ExtFuncEntityRepository;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import groovy.lang.Script;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by zouyao on 2023/06/06
 */
public interface FieldConvertor {

    /**
     * 参数扩展
     * @param context
     * @return
     */
    default Map convert(Map<String,Object> context){
        ExtFuncEntityRepository extFuncRepo = BeanFactoryUtils.getBean(ExtFuncEntityRepository.class);

        List<ExtFuncEntity> all = extFuncRepo.findAll();
        List<ExtFuncEntity> funcList = all.stream().filter(ExtFuncEntity::getEnable).collect(Collectors.toList());

        for (ExtFuncEntity entity : funcList) {
            if (StrUtil.equals( entity.getScriptType(),"groovy")){
                context.put(
                        entity.getName(),
                        groovyScriptExecutor(context,entity.getBody())
                );
                break;
            }
            throw new RuntimeException("暂不支持该脚本类型");
        }
        return context;
    }

    default Object groovyScriptExecutor(Map<String,Object> context,String scriptBody){
        // 创建GroovyShell
        GroovyShell shell = new GroovyShell();
        // 创建绑定
        Binding binding = new Binding();
        binding.setVariable("context", context);
        // 执行脚本并返回结果
        Script script = shell.parse(scriptBody);
        script.setBinding(binding);
        Object result = script.run();
        return result;
    }

}
